import modelExtend from 'dva-model-extend'
import * as operatorFriendCircleService from './services/operatorFriendCircle'
import {pageModel} from 'utils/model'
import * as employeeService from "../employee/services/employees"
import * as departmentService from '../department/services/departments'

const {query} = operatorFriendCircleService

export default modelExtend(pageModel, {
  namespace: 'operatorFriendCircle',
  state: {
    empList: [],
    departments: [],
  },
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen((location) => {
        if (location.pathname === '/operatorFriendCircle') {
          const payload = location.query || {current: 1, size: 10}
          dispatch({
            type: 'query',
            payload,
          })
          dispatch({
            type: 'init',
          })
        }
      })
    },
  },
  effects: {
    * init ({payload = {}}, {call, put}) {
      const deptResp = yield call(departmentService.query)
      yield put({
        type: 'updateState', payload: {
          departments: deptResp.data,
        },
      })
    },


    * query ({payload = {}}, {call, put}) {
      const response = yield call(query, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.records,
            pagination: {
              current: Number(payload.current) || 1,
              pageSize: Number(payload.size) || 10,
              total: data.total,
            },
          },
        })
      }
    },

    * searchEmp ({payload = {}}, {call, put}) {
      const response = yield call(employeeService.searchEmp, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'updateState',
          payload: {
            empList: data,
          },
        })
      }
    },
  },
})
